package com.huifan.demo.revenue.servyou;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author: liuchenhui
 * @create: 2019-09-03 16:10
 **/
public class ShaUtil {
    public static String getSHA256(String secret, String content) {
        try {
            String hash = "";
            Mac macSHA256 = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
            macSHA256.init(secretKey);
            byte[] bytes = macSHA256.doFinal(content.getBytes());
            hash = byteToHexString(bytes);
            return hash;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
        return "";
    }


    public static String byteToHexString(byte[] bytes) {
        StringBuffer sb = new StringBuffer(bytes.length);
        String sTemp;
        for (int i = 0; i < bytes.length; i++) {
            sTemp = Integer.toHexString(0xFF & bytes[i]);
            if (sTemp.length() < 2) {
                sb.append(0);
            }
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }

    public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException {
        String app = "HB5A2FP837F0P5H6GHEGON3530MMH8O4IJNP32F497FC";
        String ser = "29AEBI1FD75EE550705C9C5GGG0JI6191IICHBGB";
        long timestamp = System.currentTimeMillis();
        String str = app + timestamp + ser;
        System.out.println(str);
        System.out.println("======================");
        System.out.println(getSHA256(ser, str));
    }
}
